package com.wbc.demo.CompletableFutureDemo;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;


/**
 * 异步处理等待最后一个完成
 * 一个接口返回结果需要几个方法同时完成之后才可以继续，并且这几个方法执行没有先后顺序，可以使用本Demo
 */
public class CompletableFutureDemo3 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<Object> objectCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("开始启动1");
            for (int i = 0; i < 10; i++) {
                System.out.println("开始启动1:"+i);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("运行完成1");
            return "1";
        }).thenCombine(CompletableFuture.supplyAsync(() -> {
            System.out.println("开始启动");
            for (int i = 0; i < 10; i++) {
                System.out.println(i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("运行完成");
            return "2";
        }), new BiFunction<Object, Object, Object>() {
            @Override
            public Object apply(Object o, Object o2) {
                //这里写逻辑
                System.out.println("结果一：" + o);
                System.out.println("结果二：" + o2);
                return o.toString() + o2.toString();
            }
        });
        Object o = null;
        try {
            o = objectCompletableFuture.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(o);

    }




}

